package uk.co.richardwkirk.parkrun.android.dataload;


import java.util.LinkedList;
import java.util.List;

import uk.co.richardwkirk.parkrun.android.dataload.cache.AthleteCache;
import uk.co.richardwkirk.parkrun.android.storage.AthleteData;
import uk.co.richardwkirk.parkrun.android.storage.AthleteDataSource;
import uk.co.richardwkirk.parkrun.data.ParkrunDataLoadException;
import uk.co.richardwkirk.parkrun.data.athletes.AthleteSummary;
import android.content.Context;
import android.util.Log;

public class AthleteSummaryDataLoader extends ParkrunDataLoader {
    
	public class AthleteSummaryDataLoadAdapter implements LoadableParkrunDataAdapter {

		List<AthleteSummary> athletes = null;
		
		public AthleteSummaryDataLoadAdapter(List<AthleteSummary> athletes) {
			this.athletes = athletes;
		}

		@Override
		public void completeLoad() {
			for (AthleteSummary athlete : athletes) {
				completeAthleteLoad(athlete);
			}
		}

		private void completeAthleteLoad(AthleteSummary athlete) {
			// Put the athlete into our cache
			long athleteId = athlete.getAthleteId();
			AthleteCache.getSingleton().cache(String.valueOf(athleteId), athlete);
			
			// Store the data back to our athlete storage
			AthleteDataSource datasource = new AthleteDataSource(getContext());
			datasource.open();
			Log.d("PARKRUN", "Updating athlete: " + athleteId + "/" + athlete.getName() + "/" + athlete.clubStatus());
			AthleteData athleteData = new AthleteData(athleteId, athlete.getName(), athlete.clubStatus(), athlete.getPageContent());
			datasource.updateAthlete(athleteData);
			datasource.close();
		}
	}
	
	List<Long> athleteIds;
	AthleteSummaryDataLoadAdapter loadedAthleteData = null;
	
	public AthleteSummaryDataLoader(Context context, String athleteIds) {
		super(context);
		this.athleteIds = stringToLongs(athleteIds);
	}

	
	private List<Long> stringToLongs(String athleteIds) {
		List<Long> athleteIdList = new LinkedList<Long>();
		for (String athleteId : athleteIds.split(",")) {
			athleteIdList.add(Long.valueOf(athleteId));
		}
		return athleteIdList;
	}


	@Override
	protected void onStartLoading() {
		if (loadedAthleteData != null) {
			deliverResult(loadedAthleteData);
		} else {
			forceLoad();
		}
	}
	
	@Override
    public AthleteSummaryDataLoadAdapter loadInBackground() {
		// Try and load athlete data
		List<AthleteSummary> athletes = new LinkedList<AthleteSummary>();
		
		try {
			for (Long athleteId : athleteIds) {
				AthleteSummary athlete = loadAthlete(athleteId);
				athletes.add(athlete);
			}
		} catch (ParkrunDataLoadException e) {
			Log.e("PARKRUN", "Could not load athlete data", e);
		}
		
		// Return an athlete adapter
		return new AthleteSummaryDataLoadAdapter(athletes);
    }

	private AthleteSummary loadAthlete(long athleteId) throws ParkrunDataLoadException {
		AthleteSummary athlete = null;
		Log.d("PARKRUN", "Loading athlete: " + athleteId);
		
		if (forceReload == false) {
			// Do we have the athlete in our cache?
			athlete = AthleteCache.getSingleton().getItem(String.valueOf(athleteId));
			if (athlete == null) {
				// Athlete list is held in the SQL db storage
				athlete = getExistingAthlete(athleteId);
			}
		}
			
		// Do we need to reload the athlete from the web?
		if (athlete == null || athlete.hasDataExpired()) {
			athlete = loadAthleteDataFromWeb(athleteId);
		}

		return athlete;
	}


	private AthleteSummary loadAthleteDataFromWeb(long athleteId) throws ParkrunDataLoadException {
		// Create a URL for the athlete summary page
		AthleteSummary athlete = AthleteSummary.loadAthleteSummary(athleteId);
		return athlete;
	}

	private AthleteSummary getExistingAthlete(long athleteId) throws ParkrunDataLoadException {
		AthleteDataSource datasource = new AthleteDataSource(getContext());
		datasource.open();
		AthleteData athleteData = datasource.getAthlete(athleteId);
		AthleteSummary athlete = null;
		if (athleteData != null && athleteData.getData() != null) {
			athlete = AthleteSummary.createAthleteSummary(athleteId, athleteData.getData());
		}
		else {
			Log.e("PARKRUN", "Athlete not found: " + athleteId);
		}
		datasource.close();
		return athlete;
	}      
    	
}	

